
import 'package:flutter/material.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/event/event.dart';
import 'package:osc/event/event_constant.dart';
import 'package:osc/models/entity/osc_find_entity.dart';
import 'package:osc/models/entity/osc_search_list_entity.dart';
import 'package:osc/res/colors.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/ui/pages/search/search.dart';
import 'package:osc/ui/pages/post/post_detail_page.dart';
import 'package:osc/ui/pages/project/project_detail_page.dart';
import 'package:osc/ui/widgets/button/pd_button.dart';
import 'package:osc/ui/widgets/image_loader.dart';
import 'package:osc/ui/widgets/user/osc_portraint_widget.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/ui/widgets/web_scaffold.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'qr_code_scan.dart';

class Find extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return new FindState();
  }
}

class FindState extends State<Find> with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin<Find>{

  TextEditingController editingController;
  FocusNode fnCode;

  HttpRepository httpRepository;
  List<OscSearch> searchList;
  int size;
  int page = 1;

  String catalog = "news";
  String keyword;

  OscSearch oscSearch;

  List<OscWeeklyActiveUser> weeklyActiveUsers;
  List<OscFindBanner> banners;
  List<OscFindRecommendProject> recommendProjects;
  OscFindBanner recommendBanner;
  String recommendBannerImage;

  int weeklyActiveUserSize = 0;
  int bannerSize = 0;
  int recommendProjectSize = 0;

  RefreshController refreshController = RefreshController(initialRefresh: true);

  @override
  void initState() {
    super.initState();
    onBusEvent();
    editingController = new TextEditingController();
    fnCode = FocusNode();
    httpRepository = new HttpRepository();
    searchList = new List();
  }

  @override
  void dispose() {
    super.dispose();
    editingController?.dispose();
    refreshController.dispose();
    offBusEvent();
  }

  @override
  bool get wantKeepAlive => true;



  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: buildBar(),
      body: buildBody(),
    );
  }

  buildBar(){
    return PreferredSize(
      child: AppBar(
        automaticallyImplyLeading: false,
        leading: null,
        titleSpacing: 0,
        title: Row(
          children: <Widget>[
            SmallWidgets.buildActionIconButton(
              context: context,
              imageName: "ic_discover_shake",
              onTap: (){
                showTips("暂无活动");
              },
            ),
            Expanded(
              child: InkWell(
                onTap: (){
                  jump2Page(Search());
                },
                child: Ink(
                  padding: EdgeInsets.symmetric(horizontal: Dimens.gap_activity_horizontal, vertical: Dimens.gap_view_bigger),
                  decoration: BoxDecoration(
                    color: Colours.bg_page,
                    borderRadius: BorderRadius.circular(Dimens.view_radius_size_biggest),
                  ),
                  child: SmallWidgets.buildText("软件、博客、问答、用户", Colors.black26, Dimens.font_sp12),
                ),
              ),
            ),
            SmallWidgets.buildActionIconButton(
                context: context,
                imageName: "ic_discover_scan",
                onTap: (){
                  jump2Page(QrCodeScanPage());
//                  scan();
                }
            ),
          ],
        ),
      ),
      preferredSize: Size.fromHeight(Dimens.view_tab_bar_height),
    );
  }

  buildBody(){
    return SmartRefresher(
      controller: refreshController,
      enablePullUp: false,
      onRefresh: refresh,
      child: ListView(
        children: <Widget>[
          buildBanner(),
          buildRecommendBanner(),
          buildWeeklyActiveUser(),
          buildRecommendProject(),
        ],
      ),
    );
  }
  
  Widget buildBanner(){
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(left: Dimens.gap_activity_horizontal, right: Dimens.gap_activity_horizontal, top: Dimens.gap_activity_vertical, bottom: Dimens.gap_view_smaller),
      height: Dimens.view_find_banner_height,
      child: Swiper(
        onTap: (int index){

        },
        itemBuilder: (BuildContext context, int index){
          return getBannerItem(index);
        },
        itemCount: bannerSize,
        itemHeight: Dimens.view_find_banner_height,
        autoplay: bannerSize>1?true:false,
        autoplayDelay: 5000,
        pagination: SwiperPagination(
          margin: EdgeInsets.zero,
            alignment: Alignment.bottomCenter,
            builder: DotSwiperPaginationBuilder(
              color: Colors.black12,
              activeColor: Colors.green,
              size: Dimens.view_radius_size_small,
              activeSize: Dimens.view_radius_size_small,
            )
        ),
      ),
    );
  }

  Widget getBannerItem(int index){
    OscFindBanner banner = banners.elementAt(index);
    String url = banner.img;
    return InkWell(
      onTap: (){
        jump2PageByType(type: banner.objType, id: banner.objId, title: banner.title, url: banner.url);
      },
      child: Container(
        color: Colors.white,
        padding: EdgeInsets.only(bottom: Dimens.gap_activity_vertical),
        child: Stack(
          fit: StackFit.expand,
          children: <Widget>[
            ImageLoader(url: url, fit: BoxFit.cover,),
            Container(
              color: Colors.black12,
            ),
            Positioned(
              bottom: 0,
              child: Container(
                padding: EdgeInsets.all(Dimens.gap_view_bigger),
                child: SmallWidgets.buildText(banner.title, Colors.white, Dimens.font_sp14, fontWeight: FontWeight.bold),
              ),
            ),
          ],
        ),
      ),
    );
  }

  buildRecommendBanner(){
    return Offstage(
      offstage: recommendBanner == null,
      child: GestureDetector(
        onTap: (){
          if(recommendBanner != null){
            jump2PageByType(type: recommendBanner.objType, id: recommendBanner.id, title: recommendBanner.title, url: recommendBanner.url);
          }
        },
        child: Container(
          height: Dimens.view_find_banner_height,
          color: Colors.white,
          margin: EdgeInsets.symmetric(vertical: Dimens.gap_divider_height_big),
          padding: EdgeInsets.all(Dimens.gap_activity_horizontal),
          child: Stack(
            fit: StackFit.expand,
            children: <Widget>[
              ClipRRect(
                borderRadius: BorderRadius.circular(Dimens.view_radius_size_small),
                child: ImageLoader(url: recommendBannerImage, fit: BoxFit.cover,),
              ),
              Positioned(
                  top: 0,
                  left: 0,
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: Dimens.gap_view_big, vertical: Dimens.gap_view_smaller),
                    decoration: BoxDecoration(
                        color: Colors.black26,
                        borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(Dimens.view_radius_size_small),
                          bottomRight: Radius.circular(Dimens.view_radius_size_small),
                        )
                    ),
                    child: buildText(recommendBanner?.title??"", Colors.white, Dimens.font_sp12),
                  )
              ),
            ],
          ),
        ),
      ),
    );
  }

  buildWeeklyActiveUser(){
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(left: Dimens.gap_activity_horizontal, right: Dimens.gap_activity_horizontal, bottom: Dimens.gap_activity_horizontal, top: Dimens.gap_view_big),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          buildSubTitle("划水排行榜"),
          GridView.builder(
            shrinkWrap: true,
              primary: false,
              padding: EdgeInsets.only(top: Dimens.gap_view_bigger),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                crossAxisSpacing: Dimens.gap_view_big,
                childAspectRatio: 0.85,
              ),
              itemBuilder: (BuildContext context, int index){
                return buildWeeklyActiveUserItem(index);
              },
            itemCount: weeklyActiveUserSize,
          ),
        ],
      ),
    );
  }

  buildWeeklyActiveUserItem(int index){
    OscWeeklyActiveUser user = weeklyActiveUsers.elementAt(index);
    Color bgRank = Colors.orangeAccent;
    if(index == 1){
      bgRank = Colors.black12;
    } else if(index == 2){
      bgRank = Colors.amber;
    }
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(Dimens.view_radius_size_small),
        border: Border.all(
          width: Dimens.gap_divider_height_smallest,
          color: Colors.black12,
        ),
      ),
      child: Stack(
        fit: StackFit.expand,
        children: <Widget>[
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              OscPortraitWidget(id: user.id, portraitImageUrl: user.portrait,),
              Padding(
                  padding: EdgeInsets.symmetric(vertical: Dimens.gap_view_bigger, horizontal: Dimens.gap_view_normal),
                child: SmallWidgets.buildText(user.name, Colors.black, Dimens.font_sp14, fontWeight: FontWeight.bold, softWrap: true, overflow: TextOverflow.ellipsis),
              ),
              PdButton(
                  data: user.followStatus == 1?"+ 关注":"已关注",
                onTap: (){
                    reverserRelation(id: user.id, index: index);
                },
                bg: Colors.green,
              ),
            ],
          ),
          buildWeeklyActiveUserRank("${index+1}", bgRank),
        ],
      ),
    );
  }
  
  buildWeeklyActiveUserRank(String data, Color color){
    return Positioned(
        top: 0,
        left: 0,
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: Dimens.gap_view_small, vertical: Dimens.gap_view_smallest),
          decoration: BoxDecoration(
              color: color,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(Dimens.view_radius_size_small),
                bottomRight: Radius.circular(Dimens.view_radius_size_small),
              )
          ),
          child: SmallWidgets.buildText(data, Colors.white, Dimens.font_sp12, fontWeight: FontWeight.bold),
        )
    );
  }

  buildRecommendProject(){
    return Container(
      color: Colors.white,
      margin: EdgeInsets.only(top: Dimens.gap_divider_height_big),
      padding: EdgeInsets.only(left: Dimens.gap_activity_horizontal, right: Dimens.gap_activity_horizontal, bottom: Dimens.gap_activity_horizontal, top: Dimens.gap_view_big),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          buildSubTitle("精选开源软件"),
          GridView.builder(
            shrinkWrap: true,
            primary: false,
            padding: EdgeInsets.only(top: Dimens.gap_view_bigger),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              crossAxisSpacing: Dimens.gap_view_big,
              mainAxisSpacing: Dimens.gap_view_big,
              childAspectRatio: 1.6,
            ),
            itemBuilder: (BuildContext context, int index){
              return buildRecommendProjectItem(recommendProjects.elementAt(index));
            },
            itemCount: recommendProjectSize,
          ),
        ],
      ),
    );
  }


  buildRecommendProjectItem(OscFindRecommendProject project){
    double radius = Dimens.view_radius_size_small;
    return GestureDetector(
      onTap: (){
        jump2Page(ProjectDetailPage(id: project.objId));
      },
      child: Container(
        height: Dimens.view_find_banner_height,
        child: Stack(
          fit: StackFit.expand,
          children: <Widget>[
            ClipRRect(
              borderRadius: BorderRadius.circular(radius),
              child: ImageLoader(url: project.img, fit: BoxFit.cover,),
            ),
            Container(
              decoration: BoxDecoration(
                  color: Colors.black38,
                  borderRadius: BorderRadius.circular(radius),
                gradient: LinearGradient(
                    colors: [Colors.black, Color(0xee000000), Colors.black54, Colors.black38, ],
                  begin: Alignment.bottomCenter,
                  end: Alignment.topCenter,
                ),
              ),
            ),
            Positioned(
                bottom: Dimens.gap_view_normal,
                left: Dimens.gap_view_normal,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    SmallWidgets.buildText(project.name, Colors.white, Dimens.font_sp14, fontWeight: FontWeight.bold),
                    buildText(project.title, Colors.white, Dimens.font_sp12),
                  ],
                ),
            ),
          ],
        ),
      ),
    );
  }

  buildSubTitle(String data){
    return SmallWidgets.buildText(data, Colors.black, Dimens.font_sp16, fontWeight: FontWeight.bold);
  }

  buildText(String data, Color color, double fontSize){
    return SmallWidgets.buildText(data, color, fontSize);
  }


  refresh() async{
    await httpRepository.getFind().then((resp){
      if(resp != null){
        if(resp.success && resp.result != null){
          OscFindEntity entity = resp.result;
          OscFind oscFind = entity.data;
          if(entity != null){
            banners = oscFind.banners;
            weeklyActiveUsers = oscFind.weeklyActiveUsers;
            recommendProjects = oscFind.recommendProjects;
            recommendBanner = oscFind.recommendBanner;
            if(recommendBanner != null){
              recommendBannerImage = recommendBanner.img;
            }
            bannerSize = banners?.length??0;
            weeklyActiveUserSize = weeklyActiveUsers?.length??0;
            recommendProjectSize = recommendProjects?.length??0;
          }
          // mounted 为 true 表示当前页面挂在到构件树中，为 false 时未挂载当前页面
          if (mounted) {
            setState(() {
              refreshController.refreshCompleted();
            });
          }
        }
      }
    });
  }

  Future<Null> reverserRelation({@required int id, @required int index}) async{
    await httpRepository.reverseRelation(id: id).then((resp) {
      if(resp.success){
        int relation = resp.result.relation;
        showTips(relation == 1 || relation == 2?"关注成功":"取消关注");
        if(mounted){
          setState(() {
            weeklyActiveUsers.elementAt(index).followStatus = relation == 1 || relation == 2? 2 : 1;
          });
        }
      }
    });
  }

  /*scan(){
    Future<String> futureString;
    if(Platform.isAndroid) {
      futureString = new QRCodeReader()
          .setAutoFocusIntervalInMs(200) // default 5000
          .setForceAutoFocus(true) // default false
          .setTorchEnabled(true) // default false
          .setHandlePermissions(true) // default true
          .setExecuteAfterPermissionGranted(true) // default true
          .scan();
    } else {
      futureString = new QRCodeReader().scan();
    }
    int userId;
    String userIdStr;
    int startIndex = 0;
    String barcode;
    futureString.then((value){
      barcode = value;
      if(barcode.startsWith(Constant.USER_QR_CODE_PREFIX_HTTPS)){
        startIndex = Constant.USER_QR_CODE_PREFIX_HTTPS.length;
      } else if(barcode.startsWith(Constant.USER_QR_CODE_PREFIX_HTTP)){
        startIndex = Constant.USER_QR_CODE_PREFIX_HTTP.length;
      }
      userIdStr = barcode.substring(startIndex);
      userId = int.parse(userIdStr);
      jump2Page(UserProfile(userId: userId));
    });

  }*/

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }

  jump2PageByType({int type, int id, String title, String url}){
    if(type == 0){
      jump2Page(WebScaffold(title: title, url: url,));
    } else if(type == 1){
      jump2Page(ProjectDetailPage(id: id));
    } else {
      jump2Page(PostDetailPage(id: id, type: type,));
    }
  }

  jump2Page(Widget page){
    NavigatorUtil.pushPage(context, page);
  }

  onBusEvent(){
    eventBus.on(EventConstant.LOGIN_FAVORITE, (tag){
    });
  }
  offBusEvent(){
    eventBus.off(EventConstant.LOGIN_FAVORITE);
  }
}